package com.justech.eat.service.impl;

import com.justech.eat.entity.Order;
import com.justech.eat.entity.OrderDetail;
import com.justech.eat.repository.OrderDetailRepository;
import com.justech.eat.repository.OrderRepository;
import com.justech.eat.service.OrderBatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: eat-service
 * @description:
 * @author: feifei.li
 * @create: 2020-06-08 17:01
 **/
@Primary
@Service
public class OrderBatchServiceImpl implements OrderBatchService {

    @Autowired
    OrderRepository orderRepository;
    @Autowired
    OrderDetailRepository orderDetailRepository;

    @Override
    public List<Order> getByDate(String date) {
        return orderRepository.findByDate(date);
    }

    @Override
    public List<Order> add(List<Order> orders) {
        List<Order> orderList = orderRepository.saveAll(orders);
        List<OrderDetail> orderDetails = splitOrderDetail(orderList);
        orderDetailRepository.saveAll(orderDetails);
        return orderList;
    }

    private List<OrderDetail> splitOrderDetail(List<Order> orders) {
        ArrayList<OrderDetail> orderDetails = new ArrayList<>(orders.size() * 4);
        for (Order order : orders) {
            for (OrderDetail detail : order.getOrderDetails()) {
                detail.setOrderId(order.getId());
                orderDetails.add(detail);
            }
        }
        return orderDetails;
    }
}
